package com.licq.ldoc.writer.visitor.example.exampler;


import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashSet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.licq.ldoc.domain.AttributeType;
import com.licq.ldoc.domain.AttributeType.AttributeTypeDecorator;
import com.licq.ldoc.utils.BeanUtils;
import com.licq.ldoc.utils.ClassUtils;
import com.licq.ldoc.writer.visitor.example.Exampler;
import com.lowagie.text.BadElementException;

/**
 * 
 * @author liujian
 *
 */
public class WrapperAttributeExampler extends Exampler {
	private static transient Log logger = LogFactory.getLog(WrapperAttributeExampler.class);
	
	private org.dom4j.Element element;
	
	private Object object;
	
	private String property;
	
	private AttributeType type;
	
	private boolean required;

	public WrapperAttributeExampler(org.dom4j.Element element, Object object,
			String name, AttributeType type, boolean required) {
		this.element = element;
		this.object = object;
		this.property = name;
		this.type = type;
		this.required = required;
	}

	@Override
	public void create() throws BadElementException {
		Object propertyValue = super.getPropertyValue(object, property);
		if (propertyValue != null || required) {
			org.dom4j.Element ele = this.element.addElement(property);
			Object[] valueArray = null;
			if (propertyValue == null) {
				valueArray = mockPropertyValue().toArray();
			} else if (propertyValue.getClass().isArray()) {
				valueArray = (Object[]) propertyValue;
			} else {
				valueArray = ((Collection<?>) propertyValue).toArray();
			}
			for (Object value : valueArray) {
				if (value != null) {
					org.dom4j.Element innerEle = ele.addElement("element");
					Exampler exampler = new BasicAttributeExampler(innerEle, null, "value", value,
							propertyValue != null ? getInnerType() : AttributeType.STRING,
							true
					);
					exampler.create();
				}
			}
		}
	}
	
	private Collection<String> mockPropertyValue() {
		Collection<String> collection = new HashSet<String>();
		AttributeType innerType = getInnerType();
		for (int i = 0; i < 2; i++) {
			collection.add(getDefaultPropertyValue(innerType));
		}
		return collection;
	}

	private AttributeType getInnerType() {
		return ((AttributeTypeDecorator) type).getAttributeType();
	}
	
	@Override
	protected String getDefaultEnumPropValue() {
		try {
			Field wrapField = BeanUtils.getDeclaredField(object.getClass(), property);
			return ClassUtils.getWrapperNestedType(wrapField).getEnumConstants()[0].toString();
		} catch (NoSuchFieldException e) {
			if (logger.isInfoEnabled()) {
				logger.info(String.format("no enum field[%s] in class[%s].", 
						property,
						object.getClass().getName()
					)
				);
			}
			return null;
		}
	}

}
